﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Validation.Validators
{
	using System.Drawing;
	using System.IO;
	using System.Text.RegularExpressions;
	using System.Web;

	public class ImageValidator : IValidator
	{
		/// <summary>
		/// Validates the specified value.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <param name="against">The against.</param>
		/// <returns></returns>
		public bool Validate(object value, object against)
		{
			if (value == null)
			{
				return false;
			}

			var file = value as HttpPostedFileWrapper;

			if (file == null || file.ContentLength == 0)
			{
				return false;
			}

			var match = new Regex(@"image/\S+", RegexOptions.Compiled | RegexOptions.IgnoreCase).IsMatch(file.ContentType);

			if (match)
			{
				try
				{
					using (var image = Image.FromStream(file.InputStream))
					{
						file.InputStream.Seek(0L, SeekOrigin.Begin);

						image.Dispose();

						return true;
					}
				}
				catch
				{
					return false;
				}
			}

			return false;
		}
	}
}